import { _decorator, Component, Node, Label, tween, BlockInputEvents } from 'cc';
import { UIBase } from "../UIBase";

const { ccclass, property } = _decorator;

@ccclass('UILoading')
export class UILoading extends UIBase {

    @property(Node)
    public loadingNode: Node = null;

    @property(Label)
    public contentTxt: Label = null;

    @property(Node)
    public maskNode: Node = null;

    private static instance: UILoading = null;

    protected onLoad(): void {
        UILoading.instance = this;
    }

    protected onEnable(): void {
        tween(this.loadingNode)
            .repeatForever(
                tween()
                    .by(1, { angle: -360 })
            )
            .start();
    }

    protected onDisable(): void {
        tween(this.loadingNode).stop();
    }

    public static showLoading(options: { title: string, mask?: boolean }) {
        if (!UILoading.instance) {
            throw new Error("UILoading not init");
        }
        let { title, mask } = options;
        if (mask === undefined) {
            mask = true;
        }
        UILoading.instance.updateTitle(title);
        let blockInputEvents = UILoading.instance.maskNode.getComponent(BlockInputEvents);
        if (blockInputEvents) {
            blockInputEvents.enabled = mask;
        }
        UILoading.instance.node.active = true;
    }

    public static hideLoading() {
        if (UILoading.instance) {
            UILoading.instance.node.active = false;
        }
    }

    public updateTitle(title: string) {
        if (this.contentTxt) {
            this.contentTxt.string = title;
        }
    }
}